/**
 * 收藏路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 处理收藏和收藏夹相关的API请求，包括收藏添加、删除、查询、收藏夹管理等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const favoritesAPI = require('../../libs/favorites-api');

// 收藏相关路由

/**
 * 添加收藏
 * POST /favorites/add
 * @body {number} userId - 用户ID
 * @body {number} videoId - 视频ID
 * @body {number} [collectionId] - 收藏夹ID
 */
router.post('/add', async (req, res) => {
    try {
        const { userId, videoId, collectionId } = req.body;
        
        // 参数验证
        if (!userId || !videoId) {
            return res.status(400).json({
                success: false,
                message: '用户ID和视频ID不能为空'
            });
        }
        
        if (isNaN(userId) || isNaN(videoId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID和视频ID必须是数字'
            });
        }
        
        if (collectionId && isNaN(collectionId)) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID必须是数字'
            });
        }
        
        const favorite = await favoritesAPI.addFavorite({
            userId: parseInt(userId),
            videoId: parseInt(videoId),
            collectionId: collectionId ? parseInt(collectionId) : null
        });
        
        res.json({
            success: true,
            message: '收藏成功',
            data: favorite
        });
    } catch (error) {
        console.error('添加收藏失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '添加收藏失败'
        });
    }
});

/**
 * 取消收藏
 * DELETE /favorites/remove/:userId/:videoId
 * @param {number} userId - 用户ID
 * @param {number} videoId - 视频ID
 */
router.delete('/remove/:userId/:videoId', async (req, res) => {
    try {
        const { userId, videoId } = req.params;
        
        // 参数验证
        if (!userId || !videoId) {
            return res.status(400).json({
                success: false,
                message: '用户ID和视频ID不能为空'
            });
        }
        
        if (isNaN(userId) || isNaN(videoId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID和视频ID必须是数字'
            });
        }
        
        const result = await favoritesAPI.removeFavorite(
            parseInt(userId),
            parseInt(videoId)
        );
        
        res.json({
            success: true,
            message: '取消收藏成功',
            data: result
        });
    } catch (error) {
        console.error('取消收藏失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '取消收藏失败'
        });
    }
});

/**
 * 检查收藏状态
 * GET /favorites/status/:userId/:videoId
 * @param {number} userId - 用户ID
 * @param {number} videoId - 视频ID
 */
router.get('/status/:userId/:videoId', async (req, res) => {
    try {
        const { userId, videoId } = req.params;
        
        // 参数验证
        if (!userId || !videoId) {
            return res.status(400).json({
                success: false,
                message: '用户ID和视频ID不能为空'
            });
        }
        
        if (isNaN(userId) || isNaN(videoId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID和视频ID必须是数字'
            });
        }
        
        const status = await favoritesAPI.checkFavoriteStatus(
            parseInt(userId),
            parseInt(videoId)
        );
        
        res.json({
            success: true,
            data: status
        });
    } catch (error) {
        console.error('检查收藏状态失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '检查收藏状态失败'
        });
    }
});

/**
 * 获取用户收藏列表
 * GET /favorites/user/:userId
 * @param {number} userId - 用户ID
 * @query {number} [collectionId] - 收藏夹ID
 * @query {number} [page=1] - 页码
 * @query {number} [limit=20] - 每页数量
 */
router.get('/user/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { collectionId, page = 1, limit = 20 } = req.query;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (collectionId && isNaN(collectionId)) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID必须是数字'
            });
        }
        
        if (isNaN(page) || isNaN(limit)) {
            return res.status(400).json({
                success: false,
                message: '页码和每页数量必须是数字'
            });
        }
        
        const result = await favoritesAPI.getUserFavorites({
            userId: parseInt(userId),
            collectionId: collectionId ? parseInt(collectionId) : undefined,
            page: parseInt(page),
            limit: parseInt(limit)
        });
        
        res.json({
            success: true,
            data: result
        });
    } catch (error) {
        console.error('获取用户收藏列表失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取用户收藏列表失败'
        });
    }
});

/**
 * 批量检查收藏状态
 * POST /favorites/batch-status
 * @body {number} userId - 用户ID
 * @body {number[]} videoIds - 视频ID数组
 */
router.post('/batch-status', async (req, res) => {
    try {
        const { userId, videoIds } = req.body;
        
        // 参数验证
        if (!userId || !Array.isArray(videoIds)) {
            return res.status(400).json({
                success: false,
                message: '用户ID和视频ID数组不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (videoIds.some(id => isNaN(id))) {
            return res.status(400).json({
                success: false,
                message: '视频ID必须是数字'
            });
        }
        
        const statusMap = await favoritesAPI.batchCheckFavoriteStatus(
            parseInt(userId),
            videoIds.map(id => parseInt(id))
        );
        
        res.json({
            success: true,
            data: statusMap
        });
    } catch (error) {
        console.error('批量检查收藏状态失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '批量检查收藏状态失败'
        });
    }
});

/**
 * 移动收藏到其他收藏夹
 * PUT /favorites/move/:favoriteId
 * @param {number} favoriteId - 收藏ID
 * @body {number} userId - 用户ID
 * @body {number} collectionId - 新收藏夹ID
 */
router.put('/move/:favoriteId', async (req, res) => {
    try {
        const { favoriteId } = req.params;
        const { userId, collectionId } = req.body;
        
        // 参数验证
        if (!favoriteId || !userId) {
            return res.status(400).json({
                success: false,
                message: '收藏ID和用户ID不能为空'
            });
        }
        
        if (isNaN(favoriteId) || isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '收藏ID和用户ID必须是数字'
            });
        }
        
        if (collectionId && isNaN(collectionId)) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID必须是数字'
            });
        }
        
        const favorite = await favoritesAPI.moveFavorite(
            parseInt(favoriteId),
            parseInt(userId),
            collectionId ? parseInt(collectionId) : null
        );
        
        res.json({
            success: true,
            message: '移动收藏成功',
            data: favorite
        });
    } catch (error) {
        console.error('移动收藏失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '移动收藏失败'
        });
    }
});

/**
 * 获取收藏统计
 * GET /favorites/stats/:userId
 * @param {number} userId - 用户ID
 */
router.get('/stats/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        const stats = await favoritesAPI.getFavoriteStats(parseInt(userId));
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取收藏统计失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取收藏统计失败'
        });
    }
});

// 收藏夹相关路由

/**
 * 创建收藏夹
 * POST /favorites/collections/create
 * @body {number} userId - 用户ID
 * @body {string} name - 收藏夹名称
 * @body {string} [description] - 收藏夹描述
 * @body {string} [privacy='private'] - 隐私设置
 */
router.post('/collections/create', async (req, res) => {
    try {
        const { userId, name, description, privacy = 'private' } = req.body;
        
        // 参数验证
        if (!userId || !name) {
            return res.status(400).json({
                success: false,
                message: '用户ID和收藏夹名称不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (typeof name !== 'string' || name.trim().length === 0) {
            return res.status(400).json({
                success: false,
                message: '收藏夹名称必须是非空字符串'
            });
        }
        
        if (privacy && !['public', 'private'].includes(privacy)) {
            return res.status(400).json({
                success: false,
                message: '隐私设置必须是public或private'
            });
        }
        
        const collection = await favoritesAPI.createCollection({
            userId: parseInt(userId),
            name: name.trim(),
            description: description ? description.trim() : undefined,
            privacy
        });
        
        res.json({
            success: true,
            message: '创建收藏夹成功',
            data: collection
        });
    } catch (error) {
        console.error('创建收藏夹失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '创建收藏夹失败'
        });
    }
});

/**
 * 获取用户收藏夹列表
 * GET /favorites/collections/user/:userId
 * @param {number} userId - 用户ID
 * @query {number} [viewerId] - 查看者ID
 * @query {number} [page=1] - 页码
 * @query {number} [limit=20] - 每页数量
 */
router.get('/collections/user/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { viewerId, page = 1, limit = 20 } = req.query;
        
        // 参数验证
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '用户ID必须是数字'
            });
        }
        
        if (viewerId && isNaN(viewerId)) {
            return res.status(400).json({
                success: false,
                message: '查看者ID必须是数字'
            });
        }
        
        if (isNaN(page) || isNaN(limit)) {
            return res.status(400).json({
                success: false,
                message: '页码和每页数量必须是数字'
            });
        }
        
        const result = await favoritesAPI.getUserCollections({
            userId: parseInt(userId),
            viewerId: viewerId ? parseInt(viewerId) : undefined,
            page: parseInt(page),
            limit: parseInt(limit)
        });
        
        res.json({
            success: true,
            data: result
        });
    } catch (error) {
        console.error('获取用户收藏夹列表失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取用户收藏夹列表失败'
        });
    }
});

/**
 * 获取收藏夹详情
 * GET /favorites/collections/detail/:collectionId
 * @param {number} collectionId - 收藏夹ID
 * @query {number} [viewerId] - 查看者ID
 */
router.get('/collections/detail/:collectionId', async (req, res) => {
    try {
        const { collectionId } = req.params;
        const { viewerId } = req.query;
        
        // 参数验证
        if (!collectionId) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID不能为空'
            });
        }
        
        if (isNaN(collectionId)) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID必须是数字'
            });
        }
        
        if (viewerId && isNaN(viewerId)) {
            return res.status(400).json({
                success: false,
                message: '查看者ID必须是数字'
            });
        }
        
        const collection = await favoritesAPI.getCollectionDetail(
            parseInt(collectionId),
            viewerId ? parseInt(viewerId) : undefined
        );
        
        if (!collection) {
            return res.status(404).json({
                success: false,
                message: '收藏夹不存在'
            });
        }
        
        res.json({
            success: true,
            data: collection
        });
    } catch (error) {
        console.error('获取收藏夹详情失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取收藏夹详情失败'
        });
    }
});

/**
 * 更新收藏夹
 * PUT /favorites/collections/update/:collectionId
 * @param {number} collectionId - 收藏夹ID
 * @body {number} userId - 用户ID
 * @body {string} [name] - 收藏夹名称
 * @body {string} [description] - 收藏夹描述
 * @body {string} [privacy] - 隐私设置
 */
router.put('/collections/update/:collectionId', async (req, res) => {
    try {
        const { collectionId } = req.params;
        const { userId, name, description, privacy } = req.body;
        
        // 参数验证
        if (!collectionId || !userId) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID和用户ID不能为空'
            });
        }
        
        if (isNaN(collectionId) || isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID和用户ID必须是数字'
            });
        }
        
        if (name && (typeof name !== 'string' || name.trim().length === 0)) {
            return res.status(400).json({
                success: false,
                message: '收藏夹名称必须是非空字符串'
            });
        }
        
        if (privacy && !['public', 'private'].includes(privacy)) {
            return res.status(400).json({
                success: false,
                message: '隐私设置必须是public或private'
            });
        }
        
        const updateData = {};
        if (name) updateData.name = name.trim();
        if (description !== undefined) updateData.description = description ? description.trim() : '';
        if (privacy) updateData.privacy = privacy;
        
        const collection = await favoritesAPI.updateCollection(
            parseInt(collectionId),
            parseInt(userId),
            updateData
        );
        
        res.json({
            success: true,
            message: '更新收藏夹成功',
            data: collection
        });
    } catch (error) {
        console.error('更新收藏夹失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '更新收藏夹失败'
        });
    }
});

/**
 * 删除收藏夹
 * DELETE /favorites/collections/delete/:collectionId
 * @param {number} collectionId - 收藏夹ID
 * @body {number} userId - 用户ID
 */
router.delete('/collections/delete/:collectionId', async (req, res) => {
    try {
        const { collectionId } = req.params;
        const { userId } = req.body;
        
        // 参数验证
        if (!collectionId || !userId) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID和用户ID不能为空'
            });
        }
        
        if (isNaN(collectionId) || isNaN(userId)) {
            return res.status(400).json({
                success: false,
                message: '收藏夹ID和用户ID必须是数字'
            });
        }
        
        const result = await favoritesAPI.deleteCollection(
            parseInt(collectionId),
            parseInt(userId)
        );
        
        res.json({
            success: true,
            message: '删除收藏夹成功',
            data: result
        });
    } catch (error) {
        console.error('删除收藏夹失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '删除收藏夹失败'
        });
    }
});

/**
 * 获取热门公开收藏夹
 * GET /favorites/collections/popular
 * @query {number} [limit=20] - 数量限制
 * @query {string} [timeRange='7d'] - 时间范围
 */
router.get('/collections/popular', async (req, res) => {
    try {
        const { limit = 20, timeRange = '7d' } = req.query;
        
        // 参数验证
        if (isNaN(limit)) {
            return res.status(400).json({
                success: false,
                message: '数量限制必须是数字'
            });
        }
        
        if (!['1d', '7d', '30d', 'all'].includes(timeRange)) {
            return res.status(400).json({
                success: false,
                message: '时间范围必须是1d、7d、30d或all'
            });
        }
        
        const collections = await favoritesAPI.getPopularCollections({
            limit: parseInt(limit),
            timeRange
        });
        
        res.json({
            success: true,
            data: collections
        });
    } catch (error) {
        console.error('获取热门收藏夹失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '获取热门收藏夹失败'
        });
    }
});

module.exports = router;